import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'

Vue.use(VueRouter)

// 基础路由（所有用户可访问）
const baseRoutes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  }
]

// 学生路由
const studentRoutes = [
  {
    path: '/public-activities',
    name: 'PublicActivities',
    component: () => import('../views/PublicActivities.vue')
  },
  {
    path: '/public-activities/:id',
    name: 'ActivityDetail',
    component: () => import('../views/ActivityDetail.vue')
  }
]

// 管理员路由
const adminRoutes = [
  {
    path: '/activity-management',
    name: 'ActivityManagement',
    component: () => import('../views/ActivityManagement.vue'),
    meta: { requiresAdmin: true }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: baseRoutes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = !!localStorage.getItem('userRole')
  
  // 检查需要认证的路由
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next('/login')
  } 
  // 检查管理员权限
  else if (to.matched.some(record => record.meta.requiresAdmin) && 
           localStorage.getItem('userRole') !== 'admin') {
    alert('无权限访问')
    next('/')
  } else {
    next()
  }
})

// 动态添加路由
function addRoutes(role) {
  const routesToAdd = role === 'admin' ? 
    [...studentRoutes, ...adminRoutes] : 
    studentRoutes
    
  routesToAdd.forEach(route => {
    if (!router.options.routes.some(r => r.path === route.path)) {
      router.addRoute(route)
    }
  })
}

export default router;
export { addRoutes };
